<template>
  <div class="app-container">
    <el-form ref="employee" :model="employee" label-width="120px">
      <el-form-item label="员工姓名">
        <el-input v-model="employee.name" />
      </el-form-item>
      
      <el-form-item label="员工年龄">
        <el-input v-model="employee.age" />
      </el-form-item>

      <el-form-item label="用户名">
        <el-input v-model="employee.username" />
      </el-form-item>

      <el-form-item label="用户密码">
        <el-input v-model="employee.password" />
      </el-form-item>
      <el-form-item label="住址">
        <el-input v-model="employee.address" />
      </el-form-item>
      <el-form-item label="电话号码">
        <el-input v-model="employee.phone" />
      </el-form-item>
      <el-form-item label="所属部门">
        <el-select v-model="employee.departmentId" placeholder="请选择所属部门">
          <el-option v-for="department in departments" :label="department.name" :key="department.id" :value="department.id"/>
        </el-select>
      </el-form-item>

      <el-form-item label="性别">
        <el-select v-model="employee.gender">
          <el-option label="男" value="1"/>
          <el-option label="女" value="0"/>
        </el-select>
      </el-form-item>

      <el-form-item label="角色名">
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
        <div style="margin: 15px 0;"/>

        <el-checkbox-group v-model="employee.roles" @change="handleCheckedCitiesChange">
          <el-checkbox v-for="role in roles" :label="role" :key="role">{{ role.name }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="头像">
        <el-upload
          :show-file-list="false"
          :on-success="handleImageUrlSuccess"
          :before-upload="beforeAvatarUpload"
          :action="BASE_API+'/employee/system/addPhoto'"
          class="avatar-uploader">
          <img v-if="employee.photo" :src="employee.photo" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"/>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="saveOrUpdate">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>

import employeeApi from '@/api/employee'
import rolesApi from '@/api/roles'
import departmentApi from '@/api/department'

export default {
  data() {
    return {
      employee: {
        roles: [],
        photo: ''
      },
      saveBtnDisabled: false, // 保存按钮是否禁用
      BASE_API: process.env.BASE_API,
      imageUrl: null,
      roles: [],
      checkAll: false,
      isIndeterminate: true,
      departments: []
    }
  },

  // 监听器
  watch: {
    $route(to, from) {
      console.log('路由变化......')
      console.log(to)
      console.log(from)
      this.init()
    }
  },

  // 生命周期方法（在路由切换，组件不变的情况下不会被调用）
  created() {
    console.log('form created ......')
    this.init()
    this.findAllrole()
    this.findAllDepartment()
  },

  mounted() {

  },

  methods: {
    handleCheckAllChange(val) {
      this.employee.roles = val ? this.roles : []
      this.isIndeterminate = false
    },
    handleCheckedCitiesChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.roles.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.roles.length
    },
    handleImageUrlSuccess(response) {
      this.employee.photo = response.data
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!')
      // }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    },
    // 表单初始化
    init() {
      // debugger
      if (this.$route.params && this.$route.params.id) {
        const id = this.$route.params.id
        this.fetchDataById(id)
      } else {
        // 对象拓展运算符：拷贝对象，而不是赋值对象的引用
        this.employee = { roles: [], photo: '' }
        
      }
    },
    findAllrole() {
      rolesApi.findAll().then(response => {
        this.roles = response.data
      })
    },
    findAllDepartment() {
      departmentApi.findAll().then(response => {
        this.departments = response.data
      })
    },
    saveOrUpdate() {
      this.saveBtnDisabled = true // 防止表单重复提交
      if (!this.employee.id) {
        this.saveData()
      } else {
        this.updateData()
      }
    },

    // 新增
    saveData() {
      employeeApi.save(this.employee).then(response => {
        // debugger
        if (response.code) {
          this.$message({
            type: 'success',
            message: response.message
          })
          this.$router.push({ path: '/employee/list' })
        }
      })
    },

    // 根据id更新记录
    updateData() {
      employeeApi.updateById(this.employee).then(response => {
        if (response.code) {
          this.$message({
            type: 'success',
            message: response.message
          })
          this.$router.push({ path: '/employee/list' })
        }
      })
    },

    // 根据id查询记录
    fetchDataById(id) {
      employeeApi.getById(id).then(response => {
        // debugger
        this.employee = response.data
      })
    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
